package org.jeecg.modules.reportLabel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.constant.WarehouseConstant;
import org.jeecg.modules.basicCompartment.entity.BasicCompartment;
import org.jeecg.modules.basicCompartment.service.IBasicCompartmentService;
import org.jeecg.modules.basicSkuInfo.entity.BasicSkuInfo;
import org.jeecg.modules.basicSkuInfo.service.IBasicSkuInfoService;
import org.jeecg.modules.inventory.entity.InventoryInfo;
import org.jeecg.modules.inventory.service.IInventoryInfoService;
import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 标签统计报表
 * @Author: jeecg-boot
 * @Date: 2023-12-01
 * @Version: V1.0
 */
@Api(tags = "标签统计报表")
@RestController
@RequestMapping("/reportLabel/reportLabel")
@Slf4j
public class ReportLabelController extends JeecgController<ReportLabel, IReportLabelService> {
    @Autowired
    private IReportLabelService reportLabelService;
    @Autowired
    private IBasicCompartmentService basicCompartmentService;
    @Autowired
    private IInventoryInfoService inventoryInfoService;
    @Autowired
    private IBasicSkuInfoService basicSkuInfoService;

    /**
     * 分页列表查询
     *
     * @param reportLabel
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "标签统计报表-分页列表查询")
    @ApiOperation(value = "标签统计报表-分页列表查询", notes = "标签统计报表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ReportLabel reportLabel,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
        queryWrapper.gt("available_box_quantity", 0);
        Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
        IPage<ReportLabel> pageList = reportLabelService.inventoryPage(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param reportLabel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ReportLabel reportLabel) {
        // Step.1 组装查询条件
        QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<ReportLabel> pageList = reportLabelService.inventoryList(queryWrapper);
        List<ReportLabel> exportList = new ArrayList<>();

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(getId(item))).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "title"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ReportLabel.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("title" + "报表", "导出人:" + sysUser.getRealname(), "title");
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 获取对象ID
     *
     * @return
     */
    private String getId(ReportLabel item) {
        try {
            return PropertyUtils.getProperty(item, "id").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @AutoLog(value = "标签统计报表-查询该货格所有货物")
    @ApiOperation(value = "标签统计报表-查询该货格所有货物", notes = "标签统计报表-查询该货格所有货物")
    @PostMapping(value = "/getBasicCompartmentReportLabel")
    public Result<?> getBasicCompartmentReportLabel(@RequestParam(name = "compartmentCode") String compartmentCode) {
        BasicCompartment one = basicCompartmentService.getOne(new LambdaQueryWrapper<BasicCompartment>().eq(BasicCompartment::getCompartmentCode, compartmentCode));
        if (one != null) {
            List<ReportLabel> list = reportLabelService.list(new LambdaQueryWrapper<ReportLabel>()
                    .eq(ReportLabel::getWarehouseCode, WarehouseConstant.WarehouseTypeEnum.AGV.getCode())
                    .eq(ReportLabel::getCompartmentCode, compartmentCode)
                    .gt(ReportLabel::getAvailableBoxQuantity, 0)
                    .orderByDesc(ReportLabel::getCreateTime));
            return Result.OK(list);
        }
        return Result.error("请输入正确货格编码");
    }

    @AutoLog(value = "库存管理-添加库存至临时库区")
    @ApiOperation(value = "库存管理-添加库存至临时库区", notes = "库存管理-添加库存至临时库区")
    @PostMapping(value = "/saveInventoryToTemporary")
    public Result<?> saveInventoryToTemporary(String skuCode, Integer goodsQuantity) {
        ReportLabel reportLabel = reportLabelService.getOne(new LambdaQueryWrapper<ReportLabel>()
                .eq(ReportLabel::getWarehouseCode, WarehouseConstant.WarehouseTypeEnum.CONVERT.getCode())
                .eq(ReportLabel::getSkuCode, skuCode)
                .eq(ReportLabel::getInventoryBoxQuantity, 0)
                .eq(ReportLabel::getInventoryGoodsQuantity, 0)
                .eq(ReportLabel::getAvailableBoxQuantity, 0)
                .isNull(ReportLabel::getOutOrderId));
        if (null == reportLabel) {
            BasicSkuInfo skuInfo = basicSkuInfoService.list(new LambdaQueryWrapper<BasicSkuInfo>().eq(BasicSkuInfo::getSkuCode, skuCode)).get(0);

            reportLabel = new ReportLabel();
            reportLabel.setWarehouseCode(WarehouseConstant.WarehouseTypeEnum.CONVERT.getCode());
            reportLabel.setLabelNumber(skuCode);
            reportLabel.setSkuCode(skuCode);
            reportLabel.setInventoryBoxQuantity(0);
            reportLabel.setInventoryGoodsQuantity(0);
            reportLabel.setAvailableBoxQuantity(0);
            reportLabel.setAvailableGoodsQuantity(goodsQuantity);
            reportLabel.setShelfCode("-");
            reportLabel.setCompartmentCode("-");
            reportLabel.setSkuType(skuInfo.getSkuType());
            reportLabel.setInOrderId(null);
            reportLabel.setInOrderCode(null);
            reportLabel.setInDate(new Date());
            reportLabel.setContainerNo("-");
            reportLabel.setOutOrderId(null);
            reportLabelService.save(reportLabel);
        } else {
            reportLabel.setAvailableGoodsQuantity(reportLabel.getAvailableGoodsQuantity() + goodsQuantity);
            reportLabelService.updateById(reportLabel);
        }

        InventoryInfo inventoryInfo = inventoryInfoService.getOne(new LambdaQueryWrapper<InventoryInfo>()
                .eq(InventoryInfo::getWarehouseCode, WarehouseConstant.WarehouseTypeEnum.CONVERT.getCode())
                .eq(InventoryInfo::getSkuCode, skuCode)
                .eq(InventoryInfo::getInventoryBoxQuantity, 0)
                .eq(InventoryInfo::getInventoryGoodsQuantity, 0)
                .eq(InventoryInfo::getAvailableBoxQuantity, 0)
                .isNull(InventoryInfo::getOutOrderId));
        if (null == inventoryInfo) {
            inventoryInfo = new InventoryInfo();
            inventoryInfo.setWarehouseCode(WarehouseConstant.WarehouseTypeEnum.CONVERT.getCode());
            inventoryInfo.setShelfCode("-");
            inventoryInfo.setCompartmentCode("-");
            inventoryInfo.setSkuCode(skuCode);
            inventoryInfo.setInventoryBoxQuantity(0);
            inventoryInfo.setInventoryGoodsQuantity(0);
            inventoryInfo.setAvailableBoxQuantity(0);
            inventoryInfo.setAvailableGoodsQuantity(goodsQuantity);
            inventoryInfo.setEnterDate(new Date());
            inventoryInfo.setOutOrderId(null);
            inventoryInfoService.save(inventoryInfo);
        } else {
            inventoryInfo.setAvailableGoodsQuantity(inventoryInfo.getAvailableGoodsQuantity() + goodsQuantity);
            inventoryInfoService.updateById(inventoryInfo);
        }

        return Result.OK();
    }

    @AutoLog(value = "updateAvailableGoodsQuantity")
    @ApiOperation(value = "updateAvailableGoodsQuantity", notes = "updateAvailableGoodsQuantity")
    @PostMapping(value = "/updateAvailableGoodsQuantity")
    public Result<?> updateAvailableGoodsQuantity() {
        List<ReportLabel> reportLabelList = reportLabelService.list();
        for (ReportLabel reportLabel : reportLabelList) {
            BasicSkuInfo skuInfo = basicSkuInfoService.list(new LambdaQueryWrapper<BasicSkuInfo>().eq(BasicSkuInfo::getSkuCode, reportLabel.getSkuCode())).get(0);
            reportLabel.setAvailableGoodsQuantity(reportLabel.getAvailableBoxQuantity() * skuInfo.getBoxCapacity());
        }
        reportLabelService.updateBatchById(reportLabelList);

        List<InventoryInfo> inventoryInfoList = inventoryInfoService.list();
        for (InventoryInfo inventoryInfo : inventoryInfoList) {
            BasicSkuInfo skuInfo = basicSkuInfoService.list(new LambdaQueryWrapper<BasicSkuInfo>().eq(BasicSkuInfo::getSkuCode, inventoryInfo.getSkuCode())).get(0);
            inventoryInfo.setAvailableGoodsQuantity(inventoryInfo.getAvailableBoxQuantity() * skuInfo.getBoxCapacity());
        }
        inventoryInfoService.updateBatchById(inventoryInfoList);

        return Result.OK();
    }

//
//    /**
//     * 分页列表查询
//     *
//     * @param reportLabel
//     * @param pageNo
//     * @param pageSize
//     * @param req
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-分页列表查询")
//    @ApiOperation(value = "标签统计报表-分页列表查询", notes = "标签统计报表-分页列表查询")
//    @GetMapping(value = "/freezeList")
//    public Result<?> freezeList(ReportLabel reportLabel,
//                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
//                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
//                                HttpServletRequest req) {
//        QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
//        queryWrapper.in("status", "1", "2")
//                .eq("is_freeze", 0);
//        queryWrapper.orderByDesc("create_time");
//        Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
//        IPage<ReportLabel> pageList = reportLabelService.page(page, queryWrapper);
//        return Result.OK(pageList);
//    }
//
//    @AutoLog(value = "标签统计报表-分页列表查询")
//    @ApiOperation(value = "标签统计报表-分页列表查询", notes = "标签统计报表-分页列表查询")
//    @GetMapping(value = "/thawList")
//    public Result<?> thawList(ReportLabel reportLabel,
//                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
//                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
//                              HttpServletRequest req) {
//        QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, req.getParameterMap());
//        queryWrapper.in("status", "1", "2")
//                .eq("is_freeze", 1);
//        queryWrapper.orderByDesc("create_time");
//        Page<ReportLabel> page = new Page<ReportLabel>(pageNo, pageSize);
//        IPage<ReportLabel> pageList = reportLabelService.page(page, queryWrapper);
//        return Result.OK(pageList);
//    }
//
//    /**
//     *   冻结
//     *
//     * @param ids
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-冻结")
//    @ApiOperation(value = "标签统计报表-冻结", notes = "标签统计报表-冻结")
//    @PostMapping(value = "/isFreeze")
//    public Result<?> isFreeze(@RequestBody List<String> ids) {
//        UpdateWrapper<ReportLabel> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.in("id", ids);
//        updateWrapper.set("is_freeze", 1);
//        reportLabelService.update(updateWrapper);
//        return Result.OK("冻结成功！");
//    }
//
//    @AutoLog(value = "标签统计报表-解冻")
//    @ApiOperation(value = "标签统计报表-解冻", notes = "标签统计报表-解冻")
//    @PostMapping(value = "/thaw")
//    public Result<?> thaw(@RequestBody List<String> ids) {
//        UpdateWrapper<ReportLabel> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.in("id", ids);
//        updateWrapper.set("is_freeze", 0);
//        reportLabelService.update(updateWrapper);
//        return Result.OK("冻结成功！");
//    }
//
//    @PostMapping("/editNumberReplenishment")
//    public Result<?> editNumberReplenishment(@RequestBody ReportLabel reportLabel) {
//        ReportLabel byId = reportLabelService.getById(reportLabel.getId());
//        if (byId == null) {
//            return Result.error("未找到对应数据");
//        }
//        List<ReplenishmentSchedule> replenishmentSchedules = replenishmentScheduleService.selectByMainId(byId.getReplenishmentId());
//        int num = 0;
//        for (ReplenishmentSchedule replenishmentSchedule : replenishmentSchedules) {
//            if (replenishmentSchedule.getSkuCode().equals(byId.getSkuCode())) {
//                num += replenishmentSchedule.getNumber();
//            }
//        }
//        LambdaQueryWrapper<ReportLabel> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(ReportLabel::getReplenishmentId, byId.getReplenishmentId());
//        wrapper.eq(ReportLabel::getSkuCode, byId.getSkuCode());
//        List<ReportLabel> list = reportLabelService.list(wrapper);
//        int number = 0;
//        for (ReportLabel reportLabel1 : list) {
//            number += reportLabel1.getNumber();
//        }
//        if (reportLabel.getNumber() > num - number + byId.getNumber()) {
//            return Result.error("输入数量大于剩余可上架数量");
//        }
//        reportLabel.setAvailableInventory(reportLabel.getNumber());
//        reportLabelService.updateById(reportLabel);
//        if (reportLabel.getNumber() == num - number + byId.getNumber()) {
//            for (ReplenishmentSchedule replenishmentSchedule : replenishmentSchedules) {
//                if (replenishmentSchedule.getSkuCode().equals(byId.getSkuCode())) {
//                    replenishmentSchedule.setStatus(13);
//                }
//            }
//            replenishmentScheduleService.updateBatchById(replenishmentSchedules);
//            if (replenishmentSchedules.stream().allMatch(e -> 13 == e.getStatus())) {
//                Replenishment byId1 = replenishmentService.getById(byId.getReplenishmentId());
//                byId1.setStatus(13);
//                replenishmentService.updateById(byId1);
//            }
//            return Result.OK("上架成功，当前品番已全部上架", reportLabel);
//        }
//        return Result.OK("同步成功", reportLabel);
//    }
//
//    /**
//     *   添加
//     *
//     * @param reportLabel
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-添加")
//    @ApiOperation(value = "标签统计报表-添加", notes = "标签统计报表-添加")
//    @PostMapping(value = "/add")
//    public Result<?> add(@RequestBody ReportLabel reportLabel) {
//        reportLabelService.save(reportLabel);
//        return Result.OK("添加成功！");
//    }
//
//    /**
//     *  编辑
//     *
//     * @param reportLabel
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-编辑")
//    @ApiOperation(value = "标签统计报表-编辑", notes = "标签统计报表-编辑")
//    @PutMapping(value = "/edit")
//    public Result<?> edit(@RequestBody ReportLabel reportLabel) {
//        reportLabelService.updateById(reportLabel);
//        return Result.OK("编辑成功!");
//    }
//
//    /**
//     *   通过id删除
//     *
//     * @param id
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-通过id删除")
//    @ApiOperation(value = "标签统计报表-通过id删除", notes = "标签统计报表-通过id删除")
//    @DeleteMapping(value = "/delete")
//    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
//        reportLabelService.removeById(id);
//        return Result.OK("删除成功!");
//    }
//
//    /**
//     *  批量删除
//     *
//     * @param ids
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-批量删除")
//    @ApiOperation(value = "标签统计报表-批量删除", notes = "标签统计报表-批量删除")
//    @DeleteMapping(value = "/deleteBatch")
//    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        this.reportLabelService.removeByIds(Arrays.asList(ids.split(",")));
//        return Result.OK("批量删除成功!");
//    }
//
//    /**
//     * 通过id查询
//     *
//     * @param id
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-通过id查询")
//    @ApiOperation(value = "标签统计报表-通过id查询", notes = "标签统计报表-通过id查询")
//    @GetMapping(value = "/queryById")
//    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
//        ReportLabel reportLabel = reportLabelService.getById(id);
//        if (reportLabel == null) {
//            return Result.error("未找到对应数据");
//        }
//        return Result.OK(reportLabel);
//    }
//
//    /**
//     * 导出excel
//     *
//     * @param request
//     * @param reportLabel
//     */
//    @RequestMapping(value = "/exportXlsBySkuCode")
//    public ModelAndView exportXlsBySkuCode(HttpServletRequest request, ReportLabel reportLabel) {
//        // Step.1 组装查询条件
//        QueryWrapper<ReportLabel> queryWrapper = QueryGenerator.initQueryWrapper(reportLabel, request.getParameterMap());
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//        // Step.2 获取导出数据
//        List<ReportLabel> pageList = reportLabelService.list(queryWrapper);
//        List<ReportLabel> exportList = null;
//
//        // 过滤选中数据
//        String selections = request.getParameter("selections");
//        if (oConvertUtils.isNotEmpty(selections)) {
//            List<String> selectionList = Arrays.asList(selections.split(","));
//            exportList = pageList.stream().filter(item -> {
//                try {
//                    return selectionList.contains(PropertyUtils.getProperty(item, "id").toString());
//                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
//                    throw new RuntimeException(e);
//                }
//            }).collect(Collectors.toList());
//        } else {
//            exportList = pageList;
//        }
//
//        // Step.3 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        mv.addObject(NormalExcelConstants.FILE_NAME, "标签统计报表"); //此处设置的filename无效 ,前端会重更新设置一下
//        mv.addObject(NormalExcelConstants.CLASS, ReportLabel.class);
//        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
//        ExportParams exportParams=new ExportParams("标签统计报表" + "报表", "导出人:" + sysUser.getRealname(), "标签统计报表");
//        exportParams.setImageBasePath(upLoadPath);
//        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
//        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
//        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
//        return mv;
//        //return super.exportXls(request, reportLabel, ReportLabel.class, "标签统计报表");
//    }
//
//    /**
//     * 通过excel导入数据
//     *
//     * @param request
//     * @param response
//     * @return
//     */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, ReportLabel.class);
//    }
//
//    /**
//     * 通过标签号查询
//     *
//     * @param labelNumber
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-通过标签号查询")
//    @ApiOperation(value = "标签统计报表-通过标签号查询", notes = "标签统计报表-通过标签号查询")
//    @GetMapping(value = "/queryLabelNumber")
//    public Result<?> queryLabelNumber(@RequestParam(name = "labelNumber", required = true) String labelNumber, @RequestParam(name = "sign", required = true) Integer sign) {
//        LambdaQueryWrapper<ReportLabel> lqw = Wrappers.lambdaQuery(ReportLabel.class);
//        if (sign == 1) {
//            lqw.in(ReportLabel::getStatus, "1", "2");
//        }
//        lqw.eq(ReportLabel::getLabelNumber, labelNumber);
//        ReportLabel reportLabel = reportLabelService.getOne(lqw);
//        if (reportLabel == null) {
//            return Result.error("未找到对应数据");
//        }
//        return Result.OK(reportLabel);
//    }
//
//    /**
//     * 通过标签号查询
//     *
//     * @return
//     */
//    @AutoLog(value = "标签统计报表-通过标签号查询")
//    @ApiOperation(value = "标签统计报表-通过标签号查询", notes = "标签统计报表-通过标签号查询")
//    @PostMapping(value = "/queryQRCode")
//    public Result<?> queryQRCode(@RequestBody JSONObject param) {
//        String QRCode = param.getString("QRCode");
//        String compartmentCode = param.getString("compartmentCode");
//        InOrder inOrder = param.getObject("inOrder", new TypeReference<InOrder>() {
//        });
//        InOrder byId = inOrderService.getById(inOrder.getId());
//        if (byId == null || byId.getStatus() != 3) {
//            return Result.error("入库单状态错误");
//        }
//        LambdaQueryWrapper<InOrderDetail> wrapper = Wrappers.lambdaQuery(InOrderDetail.class);
//        wrapper.apply("{0} LIKE CONCAT('%', sku_code, '%')", QRCode);
//        wrapper.eq(InOrderDetail::getInOrderId, inOrder.getId());
//        List<InOrderDetail> list = inOrderDetailService.list(wrapper);
//        if (list.isEmpty()) {
//            return Result.error("未找到对应数据");
//        }
//        LambdaQueryWrapper<ReportLabel> wrapper2 = Wrappers.lambdaQuery(ReportLabel.class);
//        wrapper2.eq(ReportLabel::getBarCode, QRCode);
//        wrapper2.eq(ReportLabel::getInOrderId, inOrder.getId());
//        wrapper2.eq(ReportLabel::getCompartmentCode, compartmentCode);
//        ReportLabel reportLabel = reportLabelService.getOne(wrapper2);
//        List<ReportLabel> reportLabel1 = reportLabelService.list(new LambdaQueryWrapper<ReportLabel>().eq(ReportLabel::getBarCode, QRCode).eq(ReportLabel::getInOrderId, inOrder.getId()));
//        if (reportLabel1 != null) {
//            List<String> ids = reportLabel1.stream().map(ReportLabel::getInOrderDetailId).collect(Collectors.toList());
//            if (!ids.isEmpty()) {
//                List<InOrderDetail> list1 = inOrderDetailService.list(new LambdaQueryWrapper<InOrderDetail>().in(InOrderDetail::getId, ids));
//                if (list1.stream().allMatch(item -> item.getStatus() == 6)) {
//                    return Result.error("输入数量大于剩余可入库数量");
//                }
//            }
//        }
//        List<InOrderRules> inOrderRulesList = inOrderRulesService.list(new LambdaQueryWrapper<InOrderRules>().lt(InOrderRules::getBeginTime, LocalDateTime.now()).gt(InOrderRules::getEndTime, LocalDateTime.now()).orderByDesc(InOrderRules::getInOrderPriority));
//        outerLoop:
//        if (!inOrderRulesList.isEmpty()) {
//            for (InOrderRules orderRules : inOrderRulesList) {
//                if (orderRules.getSkuMutex() == 1) {
//                    LambdaQueryWrapper<ReportLabel> wrapper3 = Wrappers.lambdaQuery(ReportLabel.class);
//                    wrapper3.eq(ReportLabel::getCompartmentCode, compartmentCode);
//                    wrapper3.gt(ReportLabel::getAvailableInventory,0);
//                    List<ReportLabel> reportLabels = reportLabelService.list(wrapper3);
//                    for (ReportLabel label : reportLabels) {
//                        if (reportLabel == null) {
//                            InOrderDetail inOrderDetail = list.get(0);
//                            if (!inOrderDetail.getSkuCode().equals(label.getSkuCode())) {
//                                return Result.error("该货格已存在一种品番，根据品番互斥请勿将不同品番放入同一货格，请重新选择货格");
//                            }
//                        }else{
//                            if (!reportLabel.getSkuCode().equals(label.getSkuCode())) {
//                                return Result.error("该货格已存在一种品番，根据品番互斥请勿将不同品番放入同一货格，请重新选择货格");
//                            }
//                        }
//                    }
//                    break outerLoop;
//                }
//            }
//        }
//        if (reportLabel == null) {
//            InOrderDetail inOrderDetail = list.get(0);
//            reportLabel = getReportLabel(inOrder, inOrderDetail, compartmentCode);
//            reportLabel.setBarCode(QRCode);
//            reportLabelService.save(reportLabel);
//        } else {
//            reportLabel.setNumber(reportLabel.getNumber() + 1);
//            reportLabelService.updateById(reportLabel);
//        }
//        int num = 0;
//        for (InOrderDetail inOrderDetail : list) {
//            num += inOrderDetail.getBoxNumber();
//        }
//        if (num == reportLabel.getNumber()) {
//            for (InOrderDetail inOrderDetail : list) {
//                inOrderDetail.setStatus(6);
//            }
//            inOrderDetailService.updateBatchById(list);
//            List<InOrderDetail> inOrderDetails = inOrderDetailService.selectByMainId(byId.getId());
//            if (inOrderDetails.stream().allMatch(e -> e.getStatus() == 6)) {
//                byId.setStatus(6);
//                inOrderService.updateById(byId);
//            }
//            return Result.OK("上架成功，当前品番已全部上架", null);
//        }
//        return Result.OK("上架成功", null);
//    }
//
//    /**
//     *
//     * @param QRCode 二维码
//     * @param compartmentCode 货格
//     * @param replenishment 补货单
//     * @return
//     */
//    @PostMapping("/replenishment")
//    public Result<?> replenishment(@RequestParam(name = "QRCode", required = true) String QRCode,
//                                   @RequestParam(name = "compartmentCode") String compartmentCode,
//                                   @RequestBody Replenishment replenishment) {
//        Replenishment byId = replenishmentService.getById(replenishment.getId());
//        if (byId == null || byId.getStatus() != 11) {
//            return Result.error("补货单状态错误");
//        }
//        LambdaQueryWrapper<ReplenishmentSchedule> wrapper = Wrappers.lambdaQuery(ReplenishmentSchedule.class);
//        wrapper.apply("{0} LIKE CONCAT('%', sku_code, '%')", QRCode);
//        wrapper.eq(ReplenishmentSchedule::getReplenishmentId, replenishment.getId());
//        List<ReplenishmentSchedule> list = replenishmentScheduleService.list(wrapper);
//        if (list.isEmpty()) {
//            return Result.error("未找到对应数据");
//        }
//        LambdaQueryWrapper<ReportLabel> wrapper2 = Wrappers.lambdaQuery(ReportLabel.class);
//        wrapper2.eq(ReportLabel::getBarCode, QRCode);
//        wrapper2.eq(ReportLabel::getReplenishmentId, replenishment.getId());
//        wrapper2.eq(ReportLabel::getCompartmentCode, compartmentCode);
//        ReportLabel reportLabel = reportLabelService.getOne(wrapper2);
//        List<InOrderRules> inOrderRulesList = inOrderRulesService.list(new LambdaQueryWrapper<InOrderRules>().gt(InOrderRules::getBeginTime, LocalDateTime.now()).lt(InOrderRules::getEndTime, LocalDateTime.now()).orderByDesc(InOrderRules::getInOrderPriority));
//        outerLoop:
//        if (!inOrderRulesList.isEmpty()) {
//            for (InOrderRules orderRules : inOrderRulesList) {
//                if (orderRules.getSkuMutex() == 1) {
//                    LambdaQueryWrapper<ReportLabel> wrapper3 = Wrappers.lambdaQuery(ReportLabel.class);
//                    wrapper3.eq(ReportLabel::getCompartmentCode, compartmentCode);
//                    wrapper3.gt(ReportLabel::getAvailableInventory,0);
//                    List<ReportLabel> reportLabels = reportLabelService.list(wrapper3);
//                    for (ReportLabel label : reportLabels) {
//                        if (!reportLabel.getSkuCode().equals(label.getSkuCode())) {
//                            return Result.error("该货格已存在一种品番，根据品番互斥请勿将不同品番放入同一货格，请重新选择货格");
//                        }
//                    }
//                    break outerLoop;
//                }
//            }
//        }
//        if (reportLabel == null) {
//            ReplenishmentSchedule replenishmentSchedule = list.get(0);
//            String timeId = IdWorker.getTimeId();
//            reportLabel = new ReportLabel();
//            reportLabel.setSkuCode(replenishmentSchedule.getSkuCode())//品番编码
//                    .setCustomerSkuCode(replenishmentSchedule.getSkuCode2())//客户品番
//                    .setNumber(1)//件数
//                    .setAvailableInventory(1)//可用库存
//                    .setLabelNumber(replenishmentSchedule.getOriginalLabelNumber() + "_" + timeId.substring(8))//标签号
//                    .setReplenishmentId(byId.getId())//入库单id
//                    .setCompartmentCode(compartmentCode)//货位
//                    .setShelfCode(compartmentCode.substring(0, compartmentCode.length() - 3))//货架
//                    .setIsFreeze(0)//未冻结
//                    .setInDate(new Date())//入库日期
//                    .setStatus(3)//新建状态
//                    .setBarCode(QRCode);
//            reportLabelService.save(reportLabel);
//        } else {
//            reportLabel.setNumber(reportLabel.getNumber() + 1);
//            reportLabelService.updateById(reportLabel);
//        }
//        int num = 0;
//        for (ReplenishmentSchedule replenishmentSchedule : list) {
//            num += replenishmentSchedule.getNumber();
//        }
//        if (num == reportLabel.getNumber()) {
//            for (ReplenishmentSchedule replenishmentSchedule : list) {
//                replenishmentSchedule.setStatus(13);
//            }
//            replenishmentScheduleService.updateBatchById(list);
//            List<ReplenishmentSchedule> replenishmentSchedules = replenishmentScheduleService.selectByMainId(byId.getId());
//            if (replenishmentSchedules.stream().allMatch(e -> e.getStatus() == 13)) {
//                byId.setStatus(13);
//                replenishmentService.updateById(byId);
//            }
//            return Result.OK("上架成功，当前品番已全部上架", null);
//        }
//        return Result.OK("上架成功", null);
//    }
//
//    private static @NotNull ReportLabel getReportLabel(InOrder inOrder, InOrderDetail inOrderDetail, String compartmentCode) {
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
//        String dateStr = LocalDate.now().format(formatter);
//        String labelNumber = dateStr + "_" + inOrderDetail.getSkuCode() + "_" + inOrderDetail.getInOrderId();
//        ReportLabel reportLabel = new ReportLabel();
//        reportLabel.setSkuCode(inOrderDetail.getSkuCode())//品番编码
//                .setCustomerSkuCode(inOrderDetail.getCustomerSkuCode())//客户品番
//                .setNumber(1)//件数
//                .setAvailableInventory(1)//可用库存
//                .setLabelNumber(labelNumber)//标签号
//                .setInOrderId(inOrder.getId())//入库单id
//                .setBatchNumber(inOrder.getBatchNumber())//批次号
//                .setCompartmentCode(compartmentCode)//货位
//                .setShelfCode(compartmentCode.substring(0, compartmentCode.length() - 3))//货架
//                .setIsFreeze(0)//未冻结
//                .setInDate(new Date())//入库日期
//                .setStackingDate(new Date())//上架日期
////                .setSkuType(inOrder.getType())//货物类型
//                .setInOrderDetailId(inOrderDetail.getId())//子表id
//                .setArea(inOrder.getArea())//入库库区
//                .setStatus(6);//已上架
//        return reportLabel;
//    }

}
